import React, { useState, useEffect } from "react";
import { message, Tree, Empty, Spin } from "antd";
import { getDetectionPointTree, DetectionPointTreeItem } from "../../api/gis";
import "./DetectionManagement.css";
import DetectionFiles from "./DetectionFiles";
import InspectionAreaPanel from "./InspectionAreaPanel";
import DetectionPointPanel from "./DetectionPointPanel";
import DataSetPanel from "./DataSetPanel";

interface DetectionManagementProps {
  planetId: number;
}

type ManagementLevel = "inspection_area" | "detection_point" | "dataset" | "file";

interface SelectedNode {
  level: ManagementLevel;
  inspectionAreaId?: number;
  detectionPointId?: number;
  dataSetId?: number;
  title: string;
}

const DetectionManagement: React.FC<DetectionManagementProps> = ({ planetId }) => {
  // 树形数据状态
  const [treeData, setTreeData] = useState<DetectionPointTreeItem[]>([]);
  const [treeLoading, setTreeLoading] = useState(false);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [selectedNode, setSelectedNode] = useState<SelectedNode | null>(null);

  // 巡视区管理状态
  const [showInspectionAreaManagement, setShowInspectionAreaManagement] = useState(false);

  // 获取树形数据
  const fetchTreeData = async () => {
    setTreeLoading(true);
    try {
      console.log("[DetectionManagement] 开始获取树形数据, planetId:", planetId);
      const response = await getDetectionPointTree({ planet_id: planetId });
      console.log("[DetectionManagement] 树形数据响应:", response);
      if (response.code === 200) {
        setTreeData(response.data);
        console.log("[DetectionManagement] 树形数据设置成功:", response.data);
        
        // 默认全展开所有节点
        const allKeys: React.Key[] = [];
        response.data.forEach((area: DetectionPointTreeItem) => {
          // 添加第一级节点（巡视区）
          allKeys.push(`area_${area.inspection_area_id}`);
          // 添加第二级节点（探测点）
          area.detection_point_list.forEach((point) => {
            allKeys.push(`point_${point.detection_point_id}`);
            // 添加第三级节点（数据集）
            point.data_set_list.forEach((dataset) => {
              allKeys.push(`dataset_${dataset.data_set_id}`);
            });
          });
        });
        setExpandedKeys(allKeys);
      } else {
        message.error(response.msg || "获取树形数据失败");
      }
    } catch (error) {
      console.error("获取树形数据失败:", error);
      message.error((error as any)?.message || "获取树形数据失败");
    } finally {
      setTreeLoading(false);
    }
  };

  // 构建树形结构
  const buildTreeData = (data: DetectionPointTreeItem[]) => {
    return data.map((area) => ({
      title: area.inspection_area_name,
      key: `area_${area.inspection_area_id}`,
      className: "level-1-node",
      children: area.detection_point_list.map((point) => ({
        title: point.detection_point_num,
        key: `point_${point.detection_point_id}`,
        className: "level-2-node",
        // 将上级巡视区和本节点信息挂到节点，避免依赖父节点解析
        inspectionAreaId: area.inspection_area_id,
        detectionPointId: point.detection_point_id,
        children: point.data_set_list.map((dataset) => ({
          title: dataset.data_set_name,
          key: `dataset_${dataset.data_set_id}`,
          isLeaf: true,
          // 将必要的上级信息一并挂到数据集节点
          inspectionAreaId: area.inspection_area_id,
          detectionPointId: point.detection_point_id,
          dataSetId: dataset.data_set_id,
        })),
      })),
    }));
  };

  // 通过 point 节点 key 查找其所属巡视区ID
  const getAreaIdByPointKey = (pointKey: string): number | undefined => {
    const pointId = parseInt(pointKey.split("_")[1] || "0");
    for (const area of treeData) {
      const found = area.detection_point_list.find((p) => p.detection_point_id === pointId);
      if (found) return area.inspection_area_id;
    }
    return undefined;
  };

  // 通过 dataset 节点 key 查找其所属巡视区ID和探测点ID
  const getAreaPointByDatasetKey = (
    datasetKey: string
  ): { inspectionAreaId: number; detectionPointId: number } | undefined => {
    const datasetId = parseInt(datasetKey.split("_")[1] || "0");
    for (const area of treeData) {
      for (const point of area.detection_point_list) {
        const found = point.data_set_list.find((d) => d.data_set_id === datasetId);
        if (found) {
          return { inspectionAreaId: area.inspection_area_id, detectionPointId: point.detection_point_id };
        }
      }
    }
    return undefined;
  };

  // 树节点选择处理
  const handleTreeSelect = (selectedKeys: React.Key[], info: any) => {
    setSelectedKeys(selectedKeys);
    setShowInspectionAreaManagement(false);

    if (selectedKeys.length === 0) {
      setSelectedNode(null);
      return;
    }

    const key = selectedKeys[0] as string;
    const [level, id] = key.split("_");

    switch (level) {
      case "area":
        // 点击巡视区，显示该巡视区下的探测点列表
        setSelectedNode({
          level: "detection_point",
          inspectionAreaId: parseInt(id),
          title: info.node.title,
        });
        break;
      case "point":
        // 点击探测点，显示该探测点下的数据集列表
        {
          const areaId = getAreaIdByPointKey(key);
          if (!areaId) {
            message.warning("未能定位所属巡视区，请刷新重试");
            return;
          }
          console.log("[DetectionManagement] 选中探测点 -> area:", areaId, " point:", parseInt(id));
          setSelectedNode({
            level: "dataset",
            inspectionAreaId: areaId,
            detectionPointId: parseInt(id),
            title: info.node.title,
          });
        }
        break;
      case "dataset":
        // 点击数据集，显示该数据集下的数据文件列表
        {
          const ap = getAreaPointByDatasetKey(key);
          if (!ap) {
            message.warning("未能定位所属巡视区/探测点，请刷新重试");
            return;
          }
          console.log("[DetectionManagement] 选中数据集 -> area:", ap.inspectionAreaId, " point:", ap.detectionPointId, " dataset:", parseInt(id));
          setSelectedNode({
            level: "file",
            inspectionAreaId: ap.inspectionAreaId,
            detectionPointId: ap.detectionPointId,
            dataSetId: parseInt(id),
            title: info.node.title,
          });
        }
        // 数据文件管理功能暂未实现，这里可以预留
        break;
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    fetchTreeData();
  }, [planetId]);

  // 巡视区管理函数
  const handleShowInspectionAreaManagement = () => {
    setShowInspectionAreaManagement(true);
    setSelectedNode(null);
    setSelectedKeys([]);
  };


  // 渲染右侧编辑区
  const renderEditArea = () => {
    // 如果显示巡视区管理
    if (showInspectionAreaManagement) {
      return <InspectionAreaPanel planetId={planetId} onChanged={fetchTreeData} />;
    }

    // 根据选中的节点类型显示不同的管理界面
    switch (selectedNode?.level) {
      case "detection_point":
        return (
          <DetectionPointPanel
            planetId={planetId}
            inspectionAreaId={selectedNode?.inspectionAreaId as number}
            onChanged={fetchTreeData}
          />
        );

      case "dataset":
        return (
          <DataSetPanel
            planetId={planetId}
            inspectionAreaId={selectedNode?.inspectionAreaId as number}
            detectionPointId={selectedNode?.detectionPointId as number}
            onChanged={fetchTreeData}
          />
        );

      case "file":
        return (
          <DetectionFiles
            dataSetId={selectedNode?.dataSetId || 0}
            title={selectedNode?.title}
            refreshTree={fetchTreeData}
            // 传递必要的上级ID，供创建文件时使用
            planetId={planetId}
            inspectionAreaId={selectedNode?.inspectionAreaId as number}
            detectionPointId={selectedNode?.detectionPointId as number}
          />
        );

      default:
        return null;
    }
  };

  return (
    <div
      style={{
        display: "flex",
        width: "100%",
        minWidth: "1200px",
        height: "calc(100vh - 277px)", // 减去面包屑和padding的高度
        overflow: "hidden",
      }}
    >
      {/* 左侧树形结构 */}
      <div
        style={{
          width: "350px",
          flexShrink: 0,
          marginRight: "16px",
          height: "100%",
          display: "flex",
          flexDirection: "column",
        }}
      >
        <div
          className="detection-tree-container"
          style={{
            height: "100%",
            display: "flex",
            flexDirection: "column",
          }}
        >
          {/* 导航区域 */}
          <div style={{ marginBottom: 10, flexShrink: 0 }}>
            <div
              className={`detection-nav-item ${showInspectionAreaManagement ? "detection-nav-item-active" : ""}`}
              onClick={handleShowInspectionAreaManagement}
            >
              巡视区管理
            </div>
          </div>

          <div style={{ flex: 1, overflow: "auto" }}>
            <Spin spinning={treeLoading}>
              {treeData.length === 0 ? (
                <Empty description="暂无数据" />
              ) : (
                <Tree
                  blockNode
                  treeData={buildTreeData(treeData)}
                  expandedKeys={expandedKeys}
                  onExpand={setExpandedKeys}
                  selectedKeys={selectedKeys}
                  onSelect={handleTreeSelect}
                />
              )}
            </Spin>
          </div>
        </div>
      </div>

      {/* 右侧主内容区 */}
      <div
        style={{
          flex: 1,
          height: "100%",
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
        }}
      >
        {selectedNode || showInspectionAreaManagement ? (
          <div
            style={{
              height: "100%",
              display: "flex",
              flexDirection: "column",
            }}
          >
            {renderEditArea()}
          </div>
        ) : (
          <div
            style={{
              height: "100%",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: 18,
              color: "#999",
              background: "white",
            }}
          >
            请先选择左侧树节点或点击巡视区管理
          </div>
        )}
      </div>
    </div>
  );
};

export default DetectionManagement;
